package service.impl;

import service.MoralScoresService;
import service.ScholarshipEvaluationService;
import entity.*;
import mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ScholarshipEvaluationServiceImpl implements ScholarshipEvaluationService {

    @Autowired private StudentsMapper studentsMapper;
    @Autowired private MoralScoresMapper moralScoresMapper;
    @Autowired private AcademicScoresMapper academicScoresMapper;
    @Autowired private ResearchOutputsMapper researchOutputsMapper;
    @Autowired private ResearchProjectsMapper researchProjectsMapper;
    @Autowired private SocialServicesMapper socialServicesMapper;
    @Autowired private ScholarshipApplicationsMapper scholarshipApplicationsMapper;
    @Autowired
    private MoralScoresService moralScoresService;

    @Override
    public boolean isEligible(int studentId) {
        Students student = studentsMapper.selectById(studentId);
        if (student == null || "休学".equals(student.getStatus())) return false;

        List<MoralScores> moralList = moralScoresService.selectByStudentId(studentId);
        if (moralList == null || moralList.isEmpty()) return false;

        MoralScores moral = moralList.get(0);  // 取第一条记录
        if (moral.getTotalScore() == 0f) return false;

        String deduction = moral.getDeductionDesc();
        if (deduction != null && (
                deduction.contains("警告") ||
                        deduction.contains("严重警告") ||
                        deduction.contains("留校察看") ||
                        deduction.contains("开除"))) return false;

        List<AcademicScores> scores = academicScoresMapper.selectByStudentId(studentId);
        for (AcademicScores s : scores) {
            if (s.getScore().floatValue() < 60f) return false;
        }

        return true;
    }

    @Override
    public float calculateMoralScore(int studentId) {
        List<MoralScores> moralList = moralScoresService.selectByStudentId(studentId);
        if (moralList == null || moralList.isEmpty()) return 0f;

        MoralScores moral = moralList.get(0);

        float deduction = 0f;
        String deductionDesc = moral.getDeductionDesc();
        if (deductionDesc != null && deductionDesc.contains("通报批评")) {
            int count = deductionDesc.split("通报批评").length - 1;
            deduction = count * 5f;
        }

        float raw = moral.getBaseScore() + moral.getHonorScore() + moral.getAdvisorScore() - deduction;
        return Math.min(raw, 30f);
    }


    @Override
    public float calculateAcademicScore(int studentId) {
        List<AcademicScores> list = academicScoresMapper.selectByStudentId(studentId);
        double total = 0, count = 0;
        for (AcademicScores score : list) {
            if (score.getIsDegreeCourse()) {
                total += score.getScore().doubleValue();
                count++;
            }
        }
        if (count == 0) return 0f;
        return (float) (total / count);
    }

    @Override
    public float calculateResearchScore(int studentId, int gradeYear) {
        float total = 0f;

        List<ResearchOutputs> outputs = researchOutputsMapper.selectByStudentId(studentId);
        for (ResearchOutputs r : outputs) {
            String type = r.getOutputType();
            String contribution = r.getContributionType(); // 改为 String 类型
            float base = 0f;

            if ("论文".equals(type)) {
                if (contribution != null && !contribution.trim().isEmpty()) {
                    try {
                        int contribValue = Integer.parseInt(contribution);
                        switch (contribValue) {
                            case 1: base = 30f; break;
                            case 2: base = 25f; break;
                            case 3: base = 20f; break;
                            case 4: base = 15f; break;
                            case 5: base = 10f; break;
                            case 6: base = 5f; break;
                            default: base = 0f;
                        }
                        if (gradeYear == 3 && contribValue >= 1 && contribValue <= 4) {
                            base *= 1.5f;
                        }
                    } catch (NumberFormatException e) {
                        // 如果无法解析为数字，则按字符串处理
                        if ("CCF A类".equals(contribution)) base = 30f;
                        else if ("CCF B类".equals(contribution)) base = 25f;
                        else if ("CCF C类".equals(contribution)) base = 20f;
                        else if ("EI".equals(contribution)) base = 15f;
                        else if ("核心期刊".equals(contribution)) base = 10f;
                        else if ("普通期刊".equals(contribution)) base = 5f;
                        else base = 0f;
                    }
                }
            } else if ("发明专利".equals(type)) {
                if (contribution != null && !contribution.trim().isEmpty()) {
                    if ("有证书".equals(contribution) || "1".equals(contribution)) base = 5f;
                    else if ("实审阶段".equals(contribution) || "2".equals(contribution)) base = 3f;
                }
            } else if ("实用新型".equals(type)) {
                base = 2f;
            } else if ("软件著作权".equals(type)) {
                base = 1f;
            }

            total += base;
        }

        List<ResearchProjects> projects = researchProjectsMapper.selectByStudentId(studentId);
        for (ResearchProjects p : projects) {
            total += p.getScore().floatValue();
        }

        return Math.min(total, gradeYear == 2 ? 25f : 30f);
    }


    @Override
    public float calculateSocialServiceScore(int studentId) {
        List<SocialServices> list = socialServicesMapper.selectByStudentId(studentId);
        float total = 0f;
        for (SocialServices s : list) {
            total += s.getScore().floatValue();
        }
        return Math.min(total, 20f);
    }

    @Override
    public float calculateTotalScore(int studentId, int gradeYear) {
        if (!isEligible(studentId)) return 0f;

        float moral = calculateMoralScore(studentId);
        float academic = (gradeYear == 2) ? calculateAcademicScore(studentId) : 0f;
        float research = calculateResearchScore(studentId, gradeYear);
        float service = calculateSocialServiceScore(studentId);
        float total = (gradeYear == 2)
                ? moral + academic + research + service
                : moral + research + service;

        List<ScholarshipApplications> list = scholarshipApplicationsMapper.selectByStudentId(studentId);
        ScholarshipApplications existing = list.isEmpty() ? null : list.get(0);

        ScholarshipApplications app = new ScholarshipApplications();
        app.setStudentId(studentId);
        app.setYear(java.time.Year.now().getValue());
        app.setMoralScore(moral);
        app.setAcademicScore(academic);
        app.setResearchScore(research);
        app.setServiceScore(service);
        app.setTotalScore(total);
        app.setResult(total >= 60f ? "通过" : "未通过");

        if (existing == null) scholarshipApplicationsMapper.insert(app);
        else {
            app.setId(existing.getId());
            scholarshipApplicationsMapper.update(app);
        }

        return total;
    }
}
